﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Hanhud.Web.UI;
using Hanhud.Security;
using System.Text;
using Hanhud.Utils;

namespace Hanhud.Web.Pages.Membership
{
    public partial class Register : SitePage
    {
        CMembershipUser _registerUser = new CMembershipUser();

        public Register()
            : base("Membership", "Register")
        {
            Permission.BitValue = (int)EPermission.SelectAccess;
            this.Init += new EventHandler(Register_Init);
            this.Load += new EventHandler(Register_Load);
            this.PreRender += new EventHandler(Register_PreRender);
        }

        void Register_Init(object sender, EventArgs e)
        {
            
        }

        void Register_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack && !Page.IsCallback)
            {
                BindProvinceList();
            }
        }

        void Register_PreRender(object sender, EventArgs e)
        {
            if (_registerUser.Profile.Location != null)
            {
                CLocation location = _registerUser.Profile.Location;

                // Chon tinh/thanh
                try
                {
                    if (location.ProvinceCode > 0)
                    {
                        selProvince.Value = location.ProvinceCode.ToString();
                        BindDistrictList(location.ProvinceCode);

                        if (location.DistrictCode > 0)
                        {
                            selDistrict.Value = location.DistrictCode.ToString();
                            BindCommuneList(location.ProvinceCode, location.DistrictCode);

                            if (location.CommuneCode > 0)
                            {
                                selCommune.Value = location.CommuneCode.ToString();
                            }
                        }
                    }
                }
                catch
                {

                }
            }
        }

        protected void btnRegister_Click(object sender, EventArgs e)
        {
            string message = string.Empty;
            // Kiem tra du lieu dang ky' co' hop le hay ko?
            if (ValidRegisterInfo(ref message))
            {
                // Dang ky' user
                EMembershipCreateStatus createdStatus = EMembershipCreateStatus.Success;
                CMembershipUser createdUser = CMembership.CreateUser(
                        string.Format("User{0}", _registerUser.Email.GetHashCode()),
                        tbxRPassword.Value.Trim(),
                        _registerUser.Email,
                        string.Empty,
                        string.Empty,
                        false,
                        out createdStatus);

                switch (createdStatus)
                {
                    case EMembershipCreateStatus.InvalidPassword:
                        break;
                    case EMembershipCreateStatus.DuplicateEmail:
                        break;
                    case EMembershipCreateStatus.Success:
                        createdUser.Profile = _registerUser.Profile;

                        // Update user's profile
                        createdUser.UpdateProfile();

                        // Gui mail toi nguoi dang ky, yeu cau xac thuc lai email dang ky

                        // Redirect ve trang active
#if TEST
                        Response.Redirect("~/Default.aspx");
#else
                        Response.Redirect("~/Membership/Activate.aspx");
#endif

                        break;
                    default:
                        break;
                }
            }


            if (message.Length > 0)
            {
                CMessageBox.Show(Page, message);
            }
        }

        protected void btnLogIn_Click(object sender, EventArgs e)
        {

        }

        private bool ValidRegisterInfo(ref string message)
        {
            bool bValid = true;
            StringBuilder sb = new StringBuilder();

            // Lay email dang ky
            _registerUser.Email = tbxREmail.Value;
            if (string.IsNullOrEmpty(_registerUser.Email))
            {
                sb.AppendFormat(Hanhud.Web.Resources.Messages.RequiredField, "Email đăng ký");
                bValid = false;
            }
            else
                if (!CHelper.IsValidEmail(_registerUser.Email))
                {
                    sb.AppendFormat(Hanhud.Web.Resources.Messages.InvalidInputField, "Email đăng ký");
                    bValid = false;
                }

            // Lay password
            if (string.IsNullOrEmpty(tbxRPassword.Value))
            {
                sb.AppendFormat(Hanhud.Web.Resources.Messages.RequiredField, "Mật khẩu");
                bValid = false;
            }
            else
            {
                int nPasswordLength = tbxRPassword.Value.Trim().Length;
                if (nPasswordLength < 6 | nPasswordLength > 15)
                {
                    sb.AppendFormat(Hanhud.Web.Resources.Messages.InvalidInputField, "Mật khẩu");
                    bValid = false;
                }
            }

            // Lay thong tin profile
            string fullName = tbxFullName.Value.Trim();
            if (string.IsNullOrEmpty(fullName))
            {
                sb.AppendFormat(Hanhud.Web.Resources.Messages.RequiredField, "Họ tên");
                bValid = false;
            }

            string company = tbxCompany.Value.Trim();
            if (string.IsNullOrEmpty(company))
            {
                sb.AppendFormat(Hanhud.Web.Resources.Messages.RequiredField, "Tên công ty");
                bValid = false;
            }

            string wemail = tbxWEmail.Value.Trim();
            if (string.IsNullOrEmpty(wemail))
            {
                sb.AppendFormat(Hanhud.Web.Resources.Messages.RequiredField, "Email làm việc");
                bValid = false;
            }
            else if (!CHelper.IsValidEmail(wemail))
            {
                sb.AppendFormat(Hanhud.Web.Resources.Messages.InvalidInputField, "Email làm việc");
                bValid = false;
            }

            string address = tbxAddress.Value.Trim();
            if (string.IsNullOrEmpty(address))
            {
                sb.AppendFormat(Hanhud.Web.Resources.Messages.RequiredField, "Địa chỉ");
                bValid = false;
            }

            /*
             *  UN-USE CODE 
             */
            //int provinceCode = int.TryParse(selProvince.Items[selProvince.SelectedIndex].Value, out provinceCode) ? provinceCode : -1;
            //int districtCode = int.TryParse(selDistrict.Items[selDistrict.SelectedIndex].Value, out districtCode) ? districtCode : -1;
            //int communeCode = int.TryParse(selCommune.Items[selCommune.SelectedIndex].Value, out communeCode) ? communeCode : -1;

            int provinceCode = int.TryParse(selProvince.Items[selProvince.SelectedIndex].Value, out provinceCode) ? provinceCode : -1;
            int districtCode = int.TryParse(Request.Form[selDistrict.Name], out districtCode) ? districtCode : -1;
            int communeCode = int.TryParse(Request.Form[selCommune.Name], out communeCode) ? communeCode : -1;

            if (provinceCode <= 0)
            {
                sb.AppendFormat(Hanhud.Web.Resources.Messages.RequiredField, "Tỉnh/Thành");
                bValid = false;
            }

            string hPhone = tbxHPhone.Value.Trim();
            string wPhone = tbxWPhone.Value.Trim();
            if (string.IsNullOrEmpty(wPhone))
            {
                sb.AppendFormat(Hanhud.Web.Resources.Messages.RequiredField, "Điện thoại làm việc");
                bValid = false;
            }
            string fax = tbxFax.Value.Trim();

            if (bValid)
            {
                _registerUser.Profile.FullName = fullName;
                _registerUser.Profile.Company = company;
                _registerUser.Profile.Email = wemail;
                _registerUser.Profile.Address = address;
                _registerUser.Profile.Location = CLocation.GetLocationInfo(provinceCode, districtCode, communeCode);
                _registerUser.Profile.HandPhone = hPhone;
                _registerUser.Profile.WorkPhone = wPhone;
                _registerUser.Profile.Fax = fax;
            }

            message = sb.ToString();
            return bValid;
        }

        private void BindProvinceList()
        {
            selProvince.DataSource = CLocation.GetLocations();
            selProvince.DataValueField = "ProvinceCode";
            selProvince.DataTextField = "Name";
            selProvince.DataBind();

            selProvince.Items.Insert(0, new ListItem("- Tùy chọn -", "-1"));
            selProvince.SelectedIndex = -1;
        }

        private void BindDistrictList(int provinceCode)
        {
            selDistrict.DataSource = CLocation.GetLocations(provinceCode);
            selDistrict.DataValueField = "DistrictCode";
            selDistrict.DataTextField = "Name";
            selDistrict.DataBind();

            selDistrict.Items.Insert(0, new ListItem("- Tùy chọn -", "-1"));
            selDistrict.SelectedIndex = -1;
        }

        private void BindCommuneList(int provinceCode, int districtCode)
        {
            selCommune.DataSource = CLocation.GetLocations(provinceCode, districtCode);
            selCommune.DataValueField = "CommuneCode";
            selCommune.DataTextField = "Name";
            selCommune.DataBind();

            selCommune.Items.Insert(0, new ListItem("- Tùy chọn -", "-1"));
            selCommune.SelectedIndex = -1;
        }
    }
}